package com.lyy.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 数据库连接的工具类
 */
@Component
public class ConnectionUtils {

    private ThreadLocal<Connection> connectionMap=new ThreadLocal<>();

    private DataSource dataSource;

    public ConnectionUtils(DataSource dataSource){
        this.dataSource=dataSource;
    }

    /**
     * 如果是同一个线程来获取，该方法保证每次获取到的都是同一个数据库连接
     * @return
     */
    public Connection getConnection(){
        if(connectionMap.get()!=null){
            return connectionMap.get();
        }
        //获取一个数据库连接，放入线程变量中
        try {
            connectionMap.set(dataSource.getConnection());
            return connectionMap.get();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("给connectionMap中set connection失败");
        }
    }

    /**
     * 从当前线程变量中删除连接
     */
    public void remove(){
        connectionMap.remove();
    }
}
